package com.situ.mall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.mall.common.constant.MqConstant;
import com.situ.mall.common.util.MultiDelayMessage;
import com.situ.mall.order.entity.query.OrderInfoQuery;
import com.situ.mall.order.entity.vo.CartVO;
import com.situ.mall.order.entity.vo.OrderInfoVO;
import com.situ.mall.order.mapper.CartMapper;
import com.situ.mall.order.mapper.OrderItemMapper;
import com.situ.mall.pojo.entity.order.Cart;
import com.situ.mall.pojo.entity.order.OrderInfo;
import com.situ.mall.order.mapper.OrderInfoMapper;
import com.situ.mall.order.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.pojo.entity.order.OrderItem;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author Z
 * @since 2024-10-14
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private CartServiceImpl cartService;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public void add(OrderInfo orderInfo) {
        //为什么这里要上传这么多sql语句
        //2. 生成随机订单号
        String random = String.format("%06d", new Random().nextInt(1000000));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String orderNo = simpleDateFormat.format(new Date()) + random;
        System.out.println("orderNo:" + orderNo);
        orderInfo.setOrderNo(orderNo);

        //3.每遍历一次cartVO，就往order_item表里面插入一条数据
        BigDecimal totalAmount = new BigDecimal(0);

        //1. 查找所有被勾选的商品
        //首先orderInfo里有userId和地址id，目前不知道地址id有什么用
        List<CartVO> cartList = cartService.selectByUserId(orderInfo.getUserId());
        List<CartVO> cartVOS = cartList.stream().filter(cart -> cart.getChecked() == 1).collect(Collectors.toList());
       for (CartVO cartVO : cartVOS) {
           OrderItem orderItem = new OrderItem();
           orderItem.setOrderNo(orderNo);//随机生成一个OrderNo
           orderItem.setProductId(cartVO.getProductId());
           orderItem.setProductName(cartVO.getProductName());
           orderItem.setQuantity(cartVO.getQuantity());
           orderItem.setProductImage(cartVO.getProductImage());
           orderItem.setUnitPrice(cartVO.getProductPrice());
           orderItemMapper.insert(orderItem);

           //order_item中商品总价格:价格*数量
           BigDecimal itemAmount = orderItem.getUnitPrice().multiply(new BigDecimal(orderItem.getQuantity()));
           totalAmount = totalAmount.add(itemAmount);

           //删除购物车里面已经买的这件商品
            cartMapper.delete(new QueryWrapper<Cart>().eq("checked", 1));

           //生成订单减库存：feign远程调用product-service

       }
        orderInfo.setTotalAmount(totalAmount);
        System.out.println("totalAmount:"+orderInfo.getTotalAmount());
        System.out.println("怎么回事");
        orderInfoMapper.insert(orderInfo);

        //使用消息队列，延时查看订单状态信息
        //尖括号里是data的数据类型，所以是Long
        MultiDelayMessage<Long> msg = new MultiDelayMessage<>(orderInfo.getId(),10000L, 10000L, 10000L, 15000L, 15000L, 30000L, 30000L);
        //取出此次的延时时间
        int delayValue = msg.removeNextDelay().intValue();
        rabbitTemplate.convertAndSend(MqConstant.DELAY_EXCHANGE,MqConstant.DELAY_ORDER_ROUTING_KEY, msg, new MessagePostProcessor() {
            //msg传递的是我真正想发送的数据，我希望监听到的数据，即订单ID或订单编号都行，二者都是唯一的，但是还要有个延迟时间的队列
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置延时时间
                //因为每次查询的延时时间是不一样的，所以每次拿出队列的第一个数据作为此次的延时时间
                message.getMessageProperties().setDelay(delayValue);
                return message;
            }
        });
    }

    @Override
    public IPage<OrderInfoVO> list(OrderInfoQuery orderInfoQuery) {
        //return orderInfoMapper.list(orderInfoQuery);
        IPage<OrderInfoVO> page = new Page<>(orderInfoQuery.getPage(), orderInfoQuery.getLimit());
        page = orderInfoMapper.list(page,orderInfoQuery);
        return page;
    }

    @Override
    public void cancelOrder(Long orderId) {
        UpdateWrapper<OrderInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("order_status", 5).eq("id", orderId);
        orderInfoMapper.update(updateWrapper);
    }
}
